package com.jyy.prefabricated.controller;

import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.entity.SmsRecord;
import com.jyy.prefabricated.service.SmsRecordService;
import com.jyy.prefabricated.service.SmsServiceImpl;
import com.jyy.prefabricated.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * 短信发送
 * @version 1.0.0
 * @author: zjj
 */

@Slf4j
@RequestMapping("/api")
@RestController
public class SmsRecordController {

    @Autowired
    private SmsServiceImpl smsService;

    @Autowired
    private SmsRecordService smsRecordService;

    /**
     * 发送短信验证码
     * @param tel
     * @return
     */
    @GetMapping("/sendSMS")
    public AjaxResult sendSMS(@RequestParam String tel){
        log.info("REST request to send sms to : {}", tel);
        try {
            String code = KeyUtil.genUniqueCode();
            smsService.sendSMS(tel, code,1,null);
            SmsRecord smsRecord = new SmsRecord();
            smsRecord.setTel(tel);
            smsRecord.setCode(code);
            smsRecordService.insert(smsRecord);
        } catch (Exception e) {
            log.error("发送短信失败,tel:{}",tel);
            return AjaxResult.error("发送短信失败");
        }
        return AjaxResult.success();
    }

    /**
     * 查询最新验证码
     * @param tel 手机号
     * @return
     */
    @GetMapping("/selectLast")
    public AjaxResult selectLast(@RequestParam String tel){
        return AjaxResult.success(smsRecordService.selectLast(tel));
    }
}
